package com.hxzy.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.common.constants.MarketConstants;
import com.hxzy.common.constants.RedisConstants;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.controller.admin.contamer.req.ContamerSearchReq;
import com.hxzy.controller.admin.contamer.resp.ContamerResp;
import com.hxzy.controller.mobile.login.req.MobileLoginReq;
import com.hxzy.controller.mobile.login.resp.MobileLoginResp;
import com.hxzy.entity.Contamer;
import com.hxzy.mapstruct.ContamerMapStruct;
import com.hxzy.service.ContamerService;
import com.hxzy.mapper.ContamerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
* @author admin
* @description 针对表【contamer(前端用户)】的数据库操作Service实现
* @createDate 2024-02-21 11:30:40
*/
@Service
public class ContamerServiceImpl extends ServiceImpl<ContamerMapper, Contamer>
    implements ContamerService{

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<ContamerResp> search(ContamerSearchReq req) {
        return this.baseMapper.search(req);
    }

    @Override
    public MobileLoginResp login(MobileLoginReq req) {
        //验证 验证码有效性
        String redisKey= RedisConstants.CAPTCHA_PREFIX+ req.getUuid();
        Object redisValue = this.redisTemplate.opsForValue().get(redisKey);
        if(Objects.isNull(redisValue)){
            throw new ServiceException(AckCode.CODE_NOT_FOUND);
        }
        //移出验证码
        this.redisTemplate.delete(redisKey);
        if(!req.getCode().equals(redisValue.toString())){
            throw new ServiceException(AckCode.CODE_ERROR);
        }

        //查询认证
        LambdaQueryWrapper<Contamer> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Contamer::getLoginId, req.getLoginName());
        Contamer db = this.getOne(queryWrapper);
        if(Objects.isNull(db)){
            throw new ServiceException(AckCode.USERNAME_PASSWORD_ERROR);
        }

        if(!BCrypt.checkpw(req.getLoginPwd(),db.getPassword())){
            throw new ServiceException(AckCode.USERNAME_PASSWORD_ERROR);
        }

        if(MarketConstants.ACCOUT_DISABLE.equals(db.getStatus())){
            throw new ServiceException(AckCode.DEVICE_BANNED);
        }

        return ContamerMapStruct.INSTANCE.convert(db);
    }
}




